<template>
  <div class="layout-product">
    <el-form ref="form" :model="product" :rules="rules" label-position="top" size="small">
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="product.productName" auto-complete="off" placeholder="请输入产品名称测试"></el-input>
      </el-form-item>
      <!--<el-form-item label="产品分类" prop="productType">
        <el-select v-model="product.productType" placeholder="请选择产品分类" @change="productChange">
          <el-option
            filterable
            v-for="(item, index) in lookups.productType"
            :key="index"
            :label="item.itemName"
            :value="item.itemCode">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="产品子类" prop="subProductType">
        <el-select v-model="product.subProductType" placeholder="请选择产品子类">
          <el-option
            filterable
            v-for="(item, index) in subProductTypeItems"
            :key="index"
            :label="item.itemName"
            :value="item.itemCode">
          </el-option>
        </el-select>
      </el-form-item>-->
      <el-form-item label="用途" prop="userScop">
        <el-select v-model="product.userScop" placeholder="请选择用途">
          <el-option
            filterable
            v-for="(item, index) in lookups.userScop"
            :key="index"
            :label="item.itemName"
            :value="item.itemCode">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="材质" prop="material">
        <el-select v-model="product.material" placeholder="请选择材质">
          <el-option
            filterable
            v-for="(item, index) in lookups.material"
            :key="index"
            :label="item.itemName"
            :value="item.itemCode">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="形状" prop="shape">
        <el-select v-model="product.shape" placeholder="请选择形状">
          <el-option
            filterable
            v-for="(item, index) in lookups.shape"
            :key="index"
            :label="item.itemName"
            :value="item.itemCode">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="单位" prop="unit">
        <el-input v-model="product.unit" auto-complete="off" placeholder="请输入产品单位"></el-input>
      </el-form-item>
      <el-form-item label="关键字" prop="keywords">
        <el-input v-model="product.keywords" auto-complete="off" placeholder="请输入产品关键字"></el-input>
      </el-form-item>
      <el-form-item label="产品属性" prop="productSpecList">
        <product-prop ref="speclist" :pdata="product.productSpecList"></product-prop>
      </el-form-item>
   
      <el-form-item label="产品图片">
        <el-upload
          action="/file/uploadFile"
          list-type="picture-card"
          accept=".png,.jpg"
          :file-list="fileList"
          :before-upload="handleBeforeUpload"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="产品简介" prop="remarks" style="height:344px;">
        <quill-editor
          ref="quillEditor"
          v-model="product.remarks"
          :options="editorOption"
          style="height:200px;"
        ></quill-editor>
      </el-form-item>
    </el-form>
    <div class="operate-button">
      <el-button @click="handleCancel" size="small">取 消</el-button>
      <el-button type="primary" @click="handleConfirm" size="small">确 定</el-button>
    </div>
  </div>
  
</template>
<script>
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { quillEditor } from "vue-quill-editor";
import productProp from './productProp.vue'
import { getProductAttrList, createProduct,updateProduct,getDetail } from "@/api/product";
import { uploadFile, downloadFile } from '@/api/file'
import {getLookup} from '@/api/common';

const MAX_UPLOAD_IMAGE_COUNT = 3
// const LOOKUP_PRODUCT_TYPE = 'ProductType'
// const LOOKUP_SUB_PRODUCT_TYPE = 'SubProductType'
const LOOKUP_USERSCOP = 'userScop'
const LOOKUP_MATERIAL = 'material'
const LOOKUP_SHAPE = 'shape'

export default {
  name: "Product",
  components: {
    quillEditor,
    productProp
  },
  data() {
    return {
      listLoading: false,
      fileList: [],
      fileIds: [],
      editorOption: {
        placeholder: "请输入产品介绍"
      },
      product: {
        productName: "",
        // productType: '',
        // subProductType: '',
        userScop: '',
        material: '',
        shape: '',
        remarks: "",
        partner: "panhongxi",
        productSpecList: [],
        fileId: ''
      },
      specRangpage:{
        dialogVisible:false,
        adddialogVisible:false,
        object:{specCode:''}
      },
      specRangList:[],
      isCreate: true,
      newSpec:{},
      rules: {
        productName: [
          { required: true, message: "请输入产品名称", trigger: "blur" }
        ],
        // productType: [
        //   { required: true, message: "请选择产品类型", trigger: "change" }
        // ],
        // subProductType: [
        //   { required: true, message: "请选择产品子类", trigger: "change" }
        // ],
        unit: [
          { required: true, message: "请输入产品单位", trigger: "blur" }
        ],
        keywords: [
          { required: true, message: "请输入产品关键字", trigger: "blur" }
        ],
      },
      isFileUploading: false,
      attrList: [],
      brandList: [],
      lookups: {
        // productType: [],
        // subProductType: [],
        userScop: [],
        material: [],
        shape: [],
      }
    };
  },
  computed: {
    // subProductTypeItems () {
    //   let res = []
    //   if (this.product.productType) {
    //     res = this.lookups.subProductType.filter(item => item.attr1 === this.product.productType)
    //   }
    //   return res
    // }
  },
  created() {
    // 请求产品类型字典
    // getLookup(LOOKUP_PRODUCT_TYPE).then(res => {
    //   this.lookups.productType = res.data
    // })
    // 请求产品子类字典
    // getLookup(LOOKUP_SUB_PRODUCT_TYPE).then(res => {
    //   this.lookups.subProductType = res.data
    // })
    // 请求产品类型字典
    getLookup(LOOKUP_USERSCOP).then(res => {
      this.lookups.userScop = res.data
    })
    // 请求产品子类字典
    getLookup(LOOKUP_MATERIAL).then(res => {
      this.lookups.material = res.data
    })
    // 请求产品子类字典
    getLookup(LOOKUP_SHAPE).then(res => {
      this.lookups.shape = res.data
    })
    const code = this.$route.query.code || ''
    this.isCreate = !code
    if (code) {
      const key = `product-detail-${code}`
      let cache = JSON.parse(sessionStorage.getItem(key))
      if (!location.origin.includes('localhost')) {
        sessionStorage.removeItem(key)
      }
      this.product = cache
      // 处理文件预览
      this.handlerFileIds()
    }
  },
  methods: {
    // productChange () {
    //   this.product.subProductType = ''
    // },
    getProductDetail(code){
      getDetail(code).then(response=>{
        this.product = response.data
        // 处理文件预览
        this.handlerFileIds()
      })
    },

    handlerFileIds () {
      if (!this.product.fileId) {
        return
      }
      this.fileIds = this.product.fileId.split(',')
      this.product.fileId.split(',').forEach(id => {
        this.fileList.push({
          id,
          url: downloadFile(id)
        })
      })
    },

    getProductAttrList() {
      const params = { pageNum: 1, pageSize: 100 };
      getProductAttrList(params).then(response => {
        this.attrList = response.data.list;
        if(this.isCreate==false){
    var tem = this.product.productSpecList;
        this.product.productSpecList=[]
        tem.filter(item=>{
          this.attrList.filter(item1=>{
            if(item.specCode==item1.specCode){
              this.product.productSpecList.push(item1.specCode)
            }
          })
        })
        }

      });
    },
    handleBeforeUpload(){
      if (this.fileIds.length >= MAX_UPLOAD_IMAGE_COUNT) {
        this.$message.error(`最多支持上传${MAX_UPLOAD_IMAGE_COUNT}张图片`)
        return false
      }
    },
    handleRemove(file) {
      const fileId = file.id || file.response.data.fileId
      const index = this.fileIds.indexOf(fileId)
      if (index > -1) {
        this.fileIds.splice(index, 1)
      }
    },
    handleSuccess(res) {
      this.isFileUploading = false
      if (res.code === 200) {
        const fid = res.data.fileId
        this.fileIds.push(fid)
      }
    },
    handleCancel() {
      this.$router.push({
        path: "/pms/productManage"
      });
    },
    addSpecRang(val){
    this.specRangpage.dialogVisible=true;
    this.specRangList=val.ranges
    this.newSpec.specCode=val.specCode;
    this.newSpec.specName=val.specName;
     val.isEdit=false;
    },

    updateSpecName(row){
    row.isEdit=true;
    },
     addSpec(val){
    this.product.productSpecList.push({isEdit:true,isnew:true,ranges:[]});
    },
    addSpecforProduct(val){
    if(this.product.productSpecList==undefined){
      this.product.productSpecList=[]
    }
      this.product.productSpecList.push({specName:val.specName});
    },
    handleAddSpecRangValue(){
      var spec = this.product.productSpecList.filter(item=>{
        if(this.newSpec.specName==item.specName){
           return item;
        }
      })
      if(spec[0].ranges==undefined){
        spec[0].ranges=[]
      }
      var tem = Object.assign({},this.newSpec)
      spec[0].ranges.push(tem);
      
      this.specRangpage.adddialogVisible = false;
      this.newSpec.rangeValue=null
    },
    isModifySpec(oldval,newval){
    var ismodify = false;
    newval.filter(itemnew=>{
     var tem =  oldval.filter(item=>{
        if(item.specCode==itemnew.specCode){
          return itemnew
        }
      })
      if(tem = null){
       ismodify = true;
      }
    })
    },
    updateProductConfirm(params){
       updateProduct(params).then(res => {
        if (res.code === 200) {
          this.$message({
            message: this.isCreate ? '新增成功' : '修改成功',
            type: "success",
            duration: 1000
          });
          setTimeout(() => {
            this.$router.push({
              path: "/pms/productManage"
            });
          })
        } else if (res.code === 202) {
          this.$message({
            message: "产品已经存在",
            type: "error",
            duration: 1000
          });
        } else {
          this.$message({
            message: this.isCreate ? '新增失败' : '修改失败',
            type: "error",
            duration: 1000
          });
        }
      });
    },
    getSpecList () {
      let res = JSON.parse(JSON.stringify(this.$refs.speclist.listData))
      res.forEach((item, i) => {
        // 排序
        item.sort = i
        if (!item.ranges) {
          item.ranges = []
        }
        // 是否编辑
        if (item.id) {
          item.isEdit = true
        }
        // 处理range属性
        item.ranges.forEach((range, j) => {
          range.sort = j
          if (range.id) {
            range.isEdit = true
          }
        })
      })
      return res
    },
    handleConfirm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if(this.isFileUploading){
            this.$message({
              message: "产品图片上传中，请稍等",
              type: "warning",
              duration: 1000
            });
             return
          }
          if (!this.fileIds.length) {
            this.$message({
              message: "请上传产品图片",
              type: "error",
              duration: 1000
            });
            return
          }
          var params = JSON.parse(JSON.stringify(this.product));
          // 文件id
          params.fileId = this.fileIds.join()
          // 获取产品属性
          let specList = this.getSpecList()
          params.productSpecList = specList
          if(!this.isCreate){
            this.$confirm('如果产品属性发生变化，修改后会删除对应商品，是否要确认修改?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() =>{
              this.updateProductConfirm(params)
            }).catch(() => {})
          }else{
            this.updateProductConfirm(params)
          }
        }
      });
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.layout-product {
  .el-form-item {
    width: 95%;
    .el-select {
      width: 100%;
    }
  }
}
.operate-button {
  text-align: center;
  padding-bottom: 24px;
}
.layout-product /deep/ .el-form--label-top {
  .el-form-item {
    .el-form-item__label {
      padding: 0px;
    }
  }
}
</style>


